package org.arch_learn.io.netty_demo.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * Http服务器处理类
 */
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 处理channel读取就绪事件
     *
     * @param channelHandlerContext
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        //1.判断请求是否是http请求
        if (httpObject instanceof HttpRequest) {

            DefaultHttpRequest defaultHttpRequest = (DefaultHttpRequest) httpObject;
            System.out.println("浏览器请求路径为：" + defaultHttpRequest.uri());

            if (defaultHttpRequest.uri().equals("/favicon.ico")) {
                System.out.println("不响应浏览器自动请求图标。");
                return;
            }
            //2.给浏览器进行响应
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello，我是netty http服务器！", CharsetUtil.UTF_8);
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, byteBuf);
            //2.1设置响应头
            HttpHeaders headers = defaultFullHttpResponse.headers();
            headers.set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8")
                    .set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
            channelHandlerContext.writeAndFlush(defaultFullHttpResponse);
        }
    }
}
